#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
客户端缓存管理器使用示例
演示如何在实际项目中使用客户端缓存功能
"""

import sys
import os
import logging
from typing import Dict, Any, Optional

# 添加项目根目录到 Python 路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from clouds_sdk.client_cache_manager import get_cache_manager
from clouds_sdk.cloud_factory import CloudFactory

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('CacheUsageExample')


class CloudFileService:
    """云文件服务示例类"""
    
    def __init__(self):
        self.cache_manager = get_cache_manager()
        self.logger = logging.getLogger('CloudFileService')
    
    def get_authenticated_client(self, user_id: int, account_info: Dict[str, Any], 
                               auto_login: bool = True) -> Optional[Any]:
        """
        获取已认证的云存储客户端（带缓存）
        
        Args:
            user_id: 用户ID
            account_info: 账号信息，包含 id, cloud_provider, cloud_account, cloud_password, token_info
            auto_login: 是否自动登录
            
        Returns:
            云存储客户端实例，如果获取失败返回 None
        """
        try:
            # 从缓存管理器获取客户端
            client = self.cache_manager.get_client(user_id, account_info, auto_login)
            
            if client:
                self.logger.info(f"成功获取客户端: user_id={user_id}, account_id={account_info.get('id')}")
                return client
            else:
                self.logger.warning(f"获取客户端失败: user_id={user_id}, account_id={account_info.get('id')}")
                return None
                
        except Exception as e:
            self.logger.error(f"获取客户端异常: {e}")
            return None
    
    def list_files(self, user_id: int, account_info: Dict[str, Any], 
                   folder_path: str = '/') -> Dict[str, Any]:
        """
        列出文件（使用缓存的客户端）
        
        Args:
            user_id: 用户ID
            account_info: 账号信息
            folder_path: 文件夹路径
            
        Returns:
            文件列表结果
        """
        try:
            # 获取缓存的客户端
            client = self.get_authenticated_client(user_id, account_info)
            if not client:
                return {'success': False, 'error': '无法获取客户端'}
            
            # 检查登录状态
            if not client.check_login_status_only():
                self.logger.warning("客户端登录状态无效，尝试重新登录")
                if not client.login():
                    # 登录失败，从缓存中移除
                    self.cache_manager.invalidate_client(user_id, account_info.get('id'))
                    return {'success': False, 'error': '客户端登录失败'}
            
            # 获取文件列表
            files = client.get_files_standardized(folder_path)
            
            return {
                'success': True,
                'files': files,
                'folder_path': folder_path
            }
            
        except Exception as e:
            self.logger.error(f"列出文件失败: {e}")
            return {'success': False, 'error': str(e)}
    
    def create_folder(self, user_id: int, account_info: Dict[str, Any], 
                     folder_name: str, parent_path: str = '/') -> Dict[str, Any]:
        """
        创建文件夹（使用缓存的客户端）
        
        Args:
            user_id: 用户ID
            account_info: 账号信息
            folder_name: 文件夹名称
            parent_path: 父路径
            
        Returns:
            创建结果
        """
        try:
            # 获取缓存的客户端
            client = self.get_authenticated_client(user_id, account_info)
            if not client:
                return {'success': False, 'error': '无法获取客户端'}
            
            # 检查登录状态
            if not client.check_login_status_only():
                self.logger.warning("客户端登录状态无效，尝试重新登录")
                if not client.login():
                    # 登录失败，从缓存中移除
                    self.cache_manager.invalidate_client(user_id, account_info.get('id'))
                    return {'success': False, 'error': '客户端登录失败'}
            
            # 创建文件夹
            result = client.create_folder(folder_name, parent_path)
            
            return {
                'success': True,
                'result': result,
                'folder_name': folder_name,
                'parent_path': parent_path
            }
            
        except Exception as e:
            self.logger.error(f"创建文件夹失败: {e}")
            return {'success': False, 'error': str(e)}
    
    def invalidate_user_cache(self, user_id: int) -> Dict[str, Any]:
        """
        清理用户的所有缓存客户端
        
        Args:
            user_id: 用户ID
            
        Returns:
            清理结果
        """
        try:
            count = self.cache_manager.invalidate_user_clients(user_id)
            self.logger.info(f"清理用户 {user_id} 的缓存客户端: {count} 个")
            
            return {
                'success': True,
                'cleared_count': count,
                'user_id': user_id
            }
            
        except Exception as e:
            self.logger.error(f"清理用户缓存失败: {e}")
            return {'success': False, 'error': str(e)}
    
    def get_cache_status(self) -> Dict[str, Any]:
        """
        获取缓存状态
        
        Returns:
            缓存状态信息
        """
        try:
            stats = self.cache_manager.get_cache_stats()
            clients_info = self.cache_manager.get_cached_clients_info()
            
            return {
                'success': True,
                'stats': stats,
                'clients': clients_info
            }
            
        except Exception as e:
            self.logger.error(f"获取缓存状态失败: {e}")
            return {'success': False, 'error': str(e)}


def demo_usage():
    """演示使用方法"""
    logger.info("=== 客户端缓存管理器使用演示 ===")
    
    # 创建云文件服务
    service = CloudFileService()
    
    # 模拟用户和账号信息
    user_id = 1
    account_info = {
        'id': 1,
        'cloud_provider': 'tianyi',
        'cloud_account': 'demo@example.com',
        'cloud_password': 'demo_password',
        'token_info': None
    }
    
    logger.info("1. 获取缓存状态")
    status = service.get_cache_status()
    logger.info(f"缓存状态: {status}")
    
    logger.info("\n2. 尝试列出文件（会创建客户端）")
    files_result = service.list_files(user_id, account_info, '/')
    logger.info(f"文件列表结果: {files_result}")
    
    logger.info("\n3. 再次获取缓存状态（应该有缓存统计变化）")
    status = service.get_cache_status()
    logger.info(f"缓存状态: {status}")
    
    logger.info("\n4. 尝试创建文件夹")
    folder_result = service.create_folder(user_id, account_info, 'test_folder', '/')
    logger.info(f"创建文件夹结果: {folder_result}")
    
    logger.info("\n5. 清理用户缓存")
    clear_result = service.invalidate_user_cache(user_id)
    logger.info(f"清理结果: {clear_result}")
    
    logger.info("\n6. 最终缓存状态")
    status = service.get_cache_status()
    logger.info(f"最终缓存状态: {status}")


def demo_api_integration():
    """演示API集成方法"""
    logger.info("\n=== API集成演示 ===")
    
    # 这里演示如何在Flask API中使用缓存管理器
    logger.info("在Flask API中的使用方法:")
    
    api_code = '''
# 在 cloud_files.py 中的使用示例

from clouds_sdk.client_cache_manager import get_cache_manager

# 获取全局缓存管理器
cache_manager = get_cache_manager()

@bp.route('/files', methods=['GET'])
def list_files():
    try:
        user_id = get_current_user_id()
        account_id = request.args.get('account_id', type=int)
        
        # 从数据库获取账号信息
        account_info = get_account_info(user_id, account_id)
        
        # 使用缓存管理器获取客户端
        client = cache_manager.get_client(user_id, account_info)
        
        if not client:
            return jsonify({'error': '无法获取客户端'}), 400
        
        # 获取文件列表
        files = client.get_files_standardized(request.args.get('path', '/'))
        
        return jsonify({
            'success': True,
            'files': files
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/cache/status', methods=['GET'])
def get_cache_status():
    """获取缓存状态"""
    try:
        stats = cache_manager.get_cache_stats()
        clients_info = cache_manager.get_cached_clients_info()
        
        return jsonify({
            'success': True,
            'stats': stats,
            'clients': clients_info
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/cache/clear', methods=['POST'])
def clear_cache():
    """清理缓存"""
    try:
        data = request.get_json() or {}
        user_id = data.get('user_id')
        account_id = data.get('account_id')
        
        if account_id:
            # 清理指定账号
            success = cache_manager.invalidate_client(user_id, account_id)
            return jsonify({
                'success': success,
                'message': f'清理账号 {account_id} 缓存'
            })
        elif user_id:
            # 清理指定用户
            count = cache_manager.invalidate_user_clients(user_id)
            return jsonify({
                'success': True,
                'cleared_count': count,
                'message': f'清理用户 {user_id} 的所有缓存'
            })
        else:
            # 清理所有缓存
            count = cache_manager.clear_all_cache()
            return jsonify({
                'success': True,
                'cleared_count': count,
                'message': '清理所有缓存'
            })
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500
'''
    
    logger.info(api_code)


def main():
    """主函数"""
    print("客户端缓存管理器使用示例")
    print("=" * 50)
    
    try:
        # 运行基本使用演示
        demo_usage()
        
        # 运行API集成演示
        demo_api_integration()
        
        print("\n✅ 演示完成")
        
    except Exception as e:
        logger.error(f"演示过程中发生错误: {e}")
        print("\n❌ 演示失败")
        return 1
    
    return 0


if __name__ == '__main__':
    exit(main())